//
//  QuestionnaireManger.m
//  DeepBreathing
//
//  Created by rimi on 15/12/22.
//  Copyright © 2015年 rimi. All rights reserved.
//

#import "QuestionnaireManger.h"
#import "DHCAnimation.h"
#import "AnimationModel.h"
#import "PickerView.h"

#import "ControllerManager.h"
#import "RecordViewController.h"

#import "QuestionesView.h"

@interface QuestionnaireManger ()

@property(nonatomic,strong)UIView *questionnaireView;

@property(nonatomic,strong)CAGradientLayer *gradientLayer;

@property(nonatomic,strong)CAShapeLayer * maskLayer;

@property(nonatomic,strong)AnimationModel *animationModel;

@property(nonatomic,weak)UIView *superView;

@property(nonatomic,strong)UIButton *yesButton;
@property(nonatomic,strong)UIButton *noButton;

@property(nonatomic,strong)QuestionesView *quesitionView;

@property(nonatomic,strong)PickerView *pickerView;

@property (strong, nonatomic) CALayer *titleRecordedLayer;
@property(nonatomic,strong)RecordViewController *RCVC;


@end



@implementation QuestionnaireManger

+(instancetype)shareManger{
    
    
    static QuestionnaireManger *manger;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[QuestionnaireManger alloc]init];
    });
    return manger;
    
 }

#pragma  mark - getter
-(QuestionesView *)quesitionView{
    
    if (!_quesitionView) {
        _quesitionView = [[QuestionesView alloc]init];
    }
    return _quesitionView;
}

-(UIButton *)yesButton{
    
    
    
    if (!_yesButton) {
        _yesButton =  ({
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setImage:[UIImage imageNamed:@"对.png"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"对_选中.png"] forState:UIControlStateSelected];
            button.frame = CGRectMake(375-100-30, 667-100-30, 100, 100);
            [button addTarget:self action:@selector(onYES:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _yesButton;
}
- (UIButton *)noButton
{
    if (!_noButton) {
        _noButton = ({
            
            UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
            [button setImage:[UIImage imageNamed:@"错.png"] forState:UIControlStateNormal];
            [button setImage:[UIImage imageNamed:@"错_选中.png"] forState:UIControlStateSelected];
            button.frame = CGRectMake(30, 667-100-30, 100, 100);
            [button addTarget:self action:@selector(onNo:) forControlEvents:UIControlEventTouchUpInside];
            button;
        });
    }
    return _noButton;
}
-(AnimationModel *)animationModel{
    
    if (!_animationModel) {
        _animationModel = [[AnimationModel alloc]init];
    }
    return _animationModel;
}

-(CAShapeLayer *)maskLayer{
    
    if (!_maskLayer) {
        _maskLayer = ({
          
            CAShapeLayer *shape = [CAShapeLayer layer];
            shape.frame =  [UIScreen mainScreen].bounds;
            shape.fillColor = [UIColor redColor].CGColor;
            shape.backgroundColor  = [UIColor clearColor].CGColor;
            shape.strokeColor = [UIColor clearColor].CGColor;
            shape.path = self.animationModel.fromPath.CGPath;
            shape;
        
        
        
        });
    }
    return _maskLayer;
}
-(CAGradientLayer *)gradientLayer{
    
    
    if (!_gradientLayer) {
        _gradientLayer = ({
            
            CAGradientLayer *layer = [CAGradientLayer layer];
            layer.frame = [UIScreen mainScreen].bounds;
            layer.colors   = self.animationModel.orangeColors;
            layer.startPoint = CGPointMake(0, 0);
            layer.endPoint = CGPointMake(0, 1);
            layer.mask = self.maskLayer;
            layer;
        
        
        
        });
    }
    return _gradientLayer;
    
}

//picker
-(PickerView *)pickerView{
    if (!_pickerView) {
        _pickerView = [[PickerView alloc]init];
    }
    
    return _pickerView;
    
}
-(UIView *)questionnaireView{
    
    
    
    if (!_questionnaireView) {
        _questionnaireView = [[UIView alloc]initWithFrame:[UIScreen mainScreen].bounds];
        [_questionnaireView.layer addSublayer:self.gradientLayer];
    }
    
    return _questionnaireView;
}

-(void)launchAnimationWithOpration:(void(^)(void))opraiton{
    
    
    [UIView transitionWithView:self.questionnaireView duration:self.animationModel.flipAnimationDuration options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
        if (opraiton) {
            opraiton();
        }
        self.superView  = self.questionnaireView.superview;
        [self.questionnaireView removeFromSuperview];
        [[ControllerManager sharedManager].tabVC.view addSubview:self.questionnaireView];
        
    } completion:^(BOOL finished) {
        //关闭隐私动画
        [CATransaction setDisableActions:YES];
        self.maskLayer.path = self.animationModel.toPath.CGPath;
        
        DHCAnimation *animation = [DHCAnimation animationWithKeyPath:@"path" duration:self.animationModel.pathAnimationDuration fromValue:(__bridge id)self.animationModel.fromPath.CGPath completionBlock:^(BOOL flag) {
            
            [self.questionnaireView addSubview:self.quesitionView];
            
            [self.questionnaireView addSubview:self.yesButton];
            [self.questionnaireView addSubview:self.noButton];
            
            
            DHCAnimation *buttonAnimation = [DHCAnimation animationWithKeyPath:@"position.x" duration:0.5 fromValue:@(375 + 50) completionBlock:nil];
            [self.yesButton.layer addAnimation:buttonAnimation.animation forKey:nil];
            
            
            buttonAnimation.animation.fromValue = @(-50);
            [self.noButton.layer addAnimation:buttonAnimation.animation forKey:nil];
            
        }];
        
        [self.maskLayer addAnimation:animation.animation forKey:nil];
        
    }];
    
    
}

-(void)retractAnimationWithOperation:(void(^)(void))operation{
    [CATransaction setDisableActions:YES];
    self.maskLayer.path = self.animationModel.fromPath.CGPath;
    
    DHCAnimation *animation = [DHCAnimation animationWithKeyPath:@"path" duration:self.animationModel.pathAnimationDuration fromValue:(__bridge id)self.animationModel.toPath.CGPath completionBlock:^(BOOL flag) {
        
        [UIView transitionWithView:self.questionnaireView duration:self.animationModel.flipAnimationDuration options:UIViewAnimationOptionTransitionFlipFromLeft animations:^{
            if (operation) {
                operation();
            }
            [self.questionnaireView removeFromSuperview];
            [self.superView addSubview:self.questionnaireView];
        } completion:^(BOOL finished) {
            [[QuestionnaireManger shareManger].questionnaireView removeGestureRecognizer:[UIGestureRecognizer alloc]];
        }];
        
    }];
    
    [self.maskLayer addAnimation:animation.animation forKey:nil];
    
}
//block
-(void)AnimationOfColors:(NSArray *)colors completionBlock:(void(^)(void))block{
    
    DHCAnimation *animation = [DHCAnimation animationWithKeyPath:@"colors" duration:1 fromValue:colors completionBlock:^(BOOL flag) {
        if (block) {
            block();
        }
    }];
    [self.gradientLayer addAnimation:animation.animation forKey:nil];
    
    
}

-(void)onYES:(UIButton *)sender{
    
    sender.selected  =YES;
    
    [UIView animateWithDuration:0.3 animations:^{
        //平移 缩放
        sender.frame =  CGRectMake(224, 520, 110, 110);
    } completion:^(BOOL finished) {
   DHCAnimation *vertacalShake = [DHCAnimation animationWithKeyPath:@"position.y" duration:0.2 fromValue:@(sender.center.y) completionBlock:^(BOOL flag) {
       //回到原位置
       [UIView animateWithDuration:0.3 animations:^{
            sender.frame  = CGRectMake(375-100-30, 667-100-30, 100, 100);
           [self.quesitionView  loadNextQuestion];
           sender.selected  =NO;
           
           //背景颜色动画
           NSArray *fromColors;
           NSArray *toColors;
           
           if (self.quesitionView.currentIndex == 1) {
               fromColors = self.animationModel.orangeColors;
               toColors = self.animationModel.purpleColors;
               self.gradientLayer.colors = toColors;
               DHCAnimation *colorAnimation = [DHCAnimation animationWithKeyPath:@"colors" duration:0.8 fromValue:fromColors completionBlock:nil];
               colorAnimation.animation.toValue = toColors;
               [self.gradientLayer addAnimation:colorAnimation.animation forKey:nil];

           }else
           if (self.quesitionView.currentIndex == 2) {
               fromColors = self.animationModel.purpleColors;
               toColors = self.animationModel.orangeColors;
               self.gradientLayer.colors = toColors;
               DHCAnimation *colorAnimation = [DHCAnimation animationWithKeyPath:@"colors" duration:0.8 fromValue:fromColors completionBlock:nil];
               colorAnimation.animation.toValue = toColors;
               [self.gradientLayer addAnimation:colorAnimation.animation forKey:nil];

           }else
           if (self.quesitionView.currentIndex == 3) {
               [CATransaction setDisableActions:YES];
               [self AnimationOfColors:self.gradientLayer.colors completionBlock:^{
                   
                   DHCAnimation *animation = [DHCAnimation animationWithKeyPath:@"colors" duration:2 fromValue:self.gradientLayer.colors completionBlock:nil];
                   
                   animation.animation.toValue = self.animationModel.toRedColors;
                   animation.animation.repeatCount = HUGE;
                   animation.animation.autoreverses  =YES;
                   [self.gradientLayer addAnimation:animation.animation forKey:@"question4Colors"];
                   
               }];
               self.gradientLayer.colors = self.animationModel.fromRedColors;

           }else if (self.quesitionView.currentIndex == 4) {
               
               [self.gradientLayer removeAnimationForKey:@"question4Colors"];
               
               self.gradientLayer.colors = self.animationModel.orangeColors;
               //remove button
               [self gotoRecorded];
               
             [self AnimationOfColors:self.gradientLayer.colors completionBlock:^{
                 [self.quesitionView removeFromSuperview];
                 self.quesitionView = nil;
                 [self.questionnaireView.layer addSublayer:self.titleRecordedLayer];
                 DHCAnimation *animation  = [DHCAnimation animationWithKeyPath:@"position.y" duration:0.5 fromValue:@(-40) completionBlock:nil];
                 [self.titleRecordedLayer addAnimation:animation.animation forKey:nil];
                 
                 [self.questionnaireView addSubview:self.pickerView];
                 [self.pickerView.saveButton addTarget:self action:@selector(saveButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
                 [self.pickerView.giveupButton addTarget:self action:@selector(giveupButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
             }];
               
           }

           
       }];
      
            
   }];
        vertacalShake.animation.toValue = @(537 + 50);
        vertacalShake.animation.autoreverses  =YES;
        vertacalShake.animation.repeatCount  = 3;
        [sender.layer addAnimation:vertacalShake.animation forKey:nil];
    }];
    
   }

-(void)saveButtonTaped:(UIButton *)sender{
    
    
    
    
    
    
}
-(void)giveupButtonTaped:(UIButton *)sender{
    
    [self.titleRecordedLayer removeFromSuperlayer];
    [self.pickerView removeFromSuperview];
    
    [[QuestionnaireManger shareManger] retractAnimationWithOperation:^{
          [[QuestionnaireManger shareManger].questionnaireView.layer.sublayers enumerateObjectsUsingBlock:^(CALayer * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
              obj.hidden = NO;
          }];
        
        
    }];
    
    
    
}
-(void)gotoRecorded{
    
    DHCAnimation *animationYES = [DHCAnimation animationWithKeyPath:@"position.x" duration:0.3 fromValue:@(self.yesButton.layer.position.x) completionBlock:nil];
    
    self.yesButton.layer.position = CGPointMake(375+50, 589);
    [self.yesButton.layer addAnimation:animationYES.animation forKey:nil];
    DHCAnimation *animationNOB = [DHCAnimation animationWithKeyPath:@"position.x" duration:0.3 fromValue:@(self.noButton.layer.position.x) completionBlock:nil];
    self.noButton.layer.position = CGPointMake(-50, 589);
    [self.noButton.layer addAnimation:animationNOB.animation forKey:nil];
    
}

-(void)onNo:(UIButton *)sender{
    
    sender.selected  =YES;
    
    [UIView animateWithDuration:0.3 animations:^{
        //平移 缩放
        sender.frame =  CGRectMake(50, 520, 110, 110);
    } completion:^(BOOL finished) {
        DHCAnimation *vertacalShake = [DHCAnimation animationWithKeyPath:@"position.x" duration:0.2 fromValue:@(sender.center.x) completionBlock:^(BOOL flag) {
            //回到原位置
            [UIView animateWithDuration:0.3 animations:^{
                sender.frame  = CGRectMake(30, 667-100-30, 100, 100);
                [self.quesitionView  loadNextQuestion];
                sender.selected  = NO;
                
                //背景颜色动画
                NSArray *fromColors ;
                NSArray *toColors ;
                
                if (self.quesitionView.currentIndex == 1) {
                    fromColors = self.animationModel.orangeColors;
                    toColors = self.animationModel.purpleColors;
                    self.gradientLayer.colors = toColors;
                    DHCAnimation *colorAnimation = [DHCAnimation animationWithKeyPath:@"colors" duration:0.8 fromValue:fromColors completionBlock:nil];
                    colorAnimation.animation.toValue = toColors;
                    [self.gradientLayer addAnimation:colorAnimation.animation forKey:nil];
                    
                }else
                    if (self.quesitionView.currentIndex == 2) {
                        fromColors = self.animationModel.purpleColors;
                        toColors = self.animationModel.orangeColors;
                        self.gradientLayer.colors = toColors;
                        DHCAnimation *colorAnimation = [DHCAnimation animationWithKeyPath:@"colors" duration:0.8 fromValue:fromColors completionBlock:nil];
                        colorAnimation.animation.toValue = toColors;
                        [self.gradientLayer addAnimation:colorAnimation.animation forKey:nil];
                        
                    }else
                        if (self.quesitionView.currentIndex == 3) {
                            [CATransaction setDisableActions:YES];
                            [self AnimationOfColors:self.gradientLayer.colors completionBlock:^{
                                
                                DHCAnimation *animation = [DHCAnimation animationWithKeyPath:@"colors" duration:2 fromValue:self.gradientLayer.colors completionBlock:nil];
                                
                                animation.animation.toValue = self.animationModel.toRedColors;
                                animation.animation.repeatCount = HUGE;
                                animation.animation.autoreverses  =YES;
                                [self.gradientLayer addAnimation:animation.animation forKey:@"question4Colors"];
                                
                            }];
                            self.gradientLayer.colors = self.animationModel.fromRedColors;
                            
                        }else if (self.quesitionView.currentIndex == 4) {
                            
                            [self.gradientLayer removeAnimationForKey:@"question4Colors"];
                            
                            self.gradientLayer.colors = self.animationModel.orangeColors;
                            //remove button
                            [self gotoRecorded];
                            
                            [self AnimationOfColors:self.gradientLayer.colors completionBlock:^{
                                [self.quesitionView removeFromSuperview];
                                self.quesitionView = nil;
                                [self.questionnaireView.layer addSublayer:self.titleRecordedLayer];
                                DHCAnimation *animation  = [DHCAnimation animationWithKeyPath:@"position.y" duration:0.5 fromValue:@(-40) completionBlock:nil];
                                [self.titleRecordedLayer addAnimation:animation.animation forKey:nil];
                                
                                [self.questionnaireView addSubview:self.pickerView];
                                [self.pickerView.saveButton addTarget:self action:@selector(saveButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
                                [self.pickerView.giveupButton addTarget:self action:@selector(giveupButtonTaped:) forControlEvents:UIControlEventTouchUpInside];
                            }];
                            
                        }
                
                
            }];
            
            
        }];
        vertacalShake.animation.toValue = @(50);
        vertacalShake.animation.autoreverses  =YES;
        vertacalShake.animation.repeatCount  = 3;
        [sender.layer addAnimation:vertacalShake.animation forKey:nil];
    }];
    
        
}
- (CALayer *)titleRecordedLayer {
    if (!_titleRecordedLayer) {
        _titleRecordedLayer = [CALayer layer];
        _titleRecordedLayer.bounds = CGRectMake(0, 0, 280, 75);
        _titleRecordedLayer.position = CGPointMake(375.f/2, 118);
        UIGraphicsBeginImageContext(_titleRecordedLayer.bounds.size);
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        style.alignment = NSTextAlignmentCenter;
        [@"症状记录成功" drawInRect:CGRectMake(0, 0, 280, 35) withAttributes:@{NSParagraphStyleAttributeName:style, NSFontAttributeName:[UIFont systemFontOfSize:25], NSForegroundColorAttributeName:[UIColor whiteColor]}];
        [@"Synptoms are recorded" drawInRect:CGRectMake(0, 45, 280, 30) withAttributes:@{NSParagraphStyleAttributeName:style, NSFontAttributeName:[UIFont systemFontOfSize:25], NSForegroundColorAttributeName:[UIColor whiteColor]}];
        UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        _titleRecordedLayer.contents = (__bridge id)image.CGImage;
    }
    return _titleRecordedLayer;
}




@end
